/*
 * Copyright 2012-2014 the original author or authors.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.jqd.framework.core.hessian.biz.action.support;

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 
 * 比较器，用于比较实现了{@code Order}接口子类对象
 * 
 * @author liaozhicheng.cn@gmail.com
 * @date 2012-6-11
 * @since 1.0
 */
public class OrderComparator implements Comparator<Object> {
	
	private static final OrderComparator INSTANCE = new OrderComparator();
	
	
	@Override
	public int compare(Object o1, Object o2) {
		boolean b1 = o1 instanceof Order;
		boolean b2 = o2 instanceof Order;
		
		if (b1 && !b2)
			return -1;
		else if (!b1 && b2)
			return 1;
		
		int i1 = getOrder(o1);
		int i2 = getOrder(o2);
		
		return (i1 < i2) ? -1 : (i1 > i2) ? 1 : 0;
	}
	
	
	/**
	 * 对于Order对象的比较返回的是子类中设置的order值，对于其他Object对象，返回同一个值 Integer.MAX_VALUE 对于非Order对象起不到比较的作用，但也不会抛异常
	 * 
	 * @param obj
	 * @return
	 */
	protected int getOrder(Object obj) {
		return (obj instanceof Order) ? ((Order) obj).getOrder() : Order.LOWEST_PRECEDENCE;
	}
	
	
	public static void sort(List<?> list) {
		if (list.size() > 1) {
			Collections.sort(list, INSTANCE);
		}
	}
	
	
	public static void sort(Object[] array) {
		if (array.length > 1) {
			Arrays.sort(array, INSTANCE);
		}
	}
	
}
